package top.eggcode.component.query.clause;

import top.eggcode.component.query.def.LiteralSentence;
import top.eggcode.component.query.model.Expression;
import top.eggcode.component.query.predicate.CompoundPredicate;
import top.eggcode.component.query.predicate.Predicate;

import java.util.LinkedList;
import java.util.List;

/**
 * Title:
 * Description: TODO
 * Date: 2021/9/2 13:23
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public class WhereClause implements LiteralSentence {

    private final List<String> whereConditions;

    private final List<Expression<?>> parameters;

    public WhereClause() {
        this.whereConditions = new LinkedList<>();
        this.parameters = new LinkedList<>();
    }

    public WhereClause(Predicate predicate) {
        this.whereConditions = new LinkedList<>();
        this.parameters = new LinkedList<>();

        if (predicate.getClass() == CompoundPredicate.class) {
            CompoundPredicate compound = (CompoundPredicate) predicate;
            // 为空则不添加
            String expression = compound.render().trim();
            if (!"".equals(expression)) {
                whereConditions.add(expression);
            }
            parameters.addAll(compound.getParameters());
        }

    }

    public List<Expression<?>> getParameters() {
        return parameters;
    }

    @Override
    public String render() {

        if (whereConditions.size() == 0) {
            return "";
        }
        StringBuilder whereClause = new StringBuilder();
        whereConditions.forEach(condition -> {
            whereClause.append(" ").append(condition);
        });
        if ("".equals(whereClause.toString())) {
            return "";
        } else {
            return "WHERE" + whereClause.toString();
        }

    }

}
